from datetime import datetime, timedelta

from django.core.cache import cache
from django.core.mail import send_mail
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader
from django.urls import reverse

from App2.models import Student

# Create your views here.
from django.views.decorators.cache import cache_page


#对视图函数进行缓存
# @cache_page(20)  #缓存20秒,20秒内刷新不变，20秒后刷新发生变化
# def index(request):
#     current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#     print(current_time)
#     return render(request,'index.html',locals())
from App2.utils import token_confirm
from Demo5.settings import EMAIL_FROM


def index(request):
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    pre_time = datetime.now() - timedelta(days=3)
    pre_time = pre_time.strftime("%Y-%m-%d %H:%M:%S")
    return render(request,'index2.html',locals())


def cacheWeb(request):
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return HttpResponse(current_time)

#对数据进行缓存
def cacheData(request):
    #首先判断数据是否在缓存当中，如果在就直接获取
    users = cache.get("all_users")   #可以直接将结果进行序列化
    print(users)
    if not users:  #如果不在缓存中，查询数据库，将结果写入缓存
        print('正在进行数据库的查询！')
        users = Student.objects.all()
        cache.set('all_users',users)

    return render(request,'index3.html',locals())


def check_user(request):  #向邮箱中发送验证邮件
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        #验证用户是否存在
        user = Student.objects.filter(username=username).first()
        if user:   #如果用户存在
            return render(request,'register.html',{'msg':'用户名已存在'})
        else:
            #用户不存在则保存该用户
            user = Student.objects.create(username=username,password=password,is_active=0)   #0表示False 表示该用户此时没有激活

            #发送邮件 激活用户
            token = token_confirm.generate_validate_token(user.username)   #使用用户名生成token
            print(token)   #IueroOmxvOWTpSI.YDHFOA.-801K8mCj7nMQ82TZ3E1fv_ebJ4
            link = reverse("App2:active_user",kwargs={'token':token})
            #构造验证url
            url = "http://"+request.get_host()+link
            print(url)
            #加载模板
            html = loader.get_template('active.html').render({'url':url})
            #发送邮件
            send_mail(subject="账号激活",message=None,from_email=EMAIL_FROM,html_message=html,recipient_list=['2066861081@qq.com'])
            return HttpResponse('激活邮件已发送，请登录邮箱确认激活')

    return render(request, 'register.html')

def active_user(request,token):
    #函数的逻辑：从token中解析出用户的信息，在数据库中进行查询，查询成功，则将is_active置为1，表示验证成功，返回验证成功信息，跳转登录页面
    #如果验证不成功，返回错误信息，删除token信息,并跳转值注册页面，重新进行登录
    try:
        username = token_confirm.confirm_validate_token(token)
    except:
        # 出错则需要移除token信息，从数据库中将该用户删除,返回注册页面
        try:
            username = token_confirm.remove_validate_token(token)
            users = Student.objects.filter(username=username)
            for user in users:
                user.delete()
        except:
            pass
        return render(request,'message.html',{
            'message':"对不起，验证链接已过期，请重新<a href='app2/checkuser/'>注册</a>"
        })
    try:
        #在数据库中查询，该用户
        user = Student.objects.get(username=username)
    except Student.DoesNotExist:
        return render(request,'message.html', {
            'message': "对不起，你所验证的用户不存在，请重新<a href='app2/checkuser/'>注册</a>"
        })

    user.is_active = 1  #激活用户
    user.save()
    return render(request, 'message.html', {
        'message': "验证成功请跳转登录页进行登录<a href='app2/login/'>登录</a>"
    })


def user_login(request):
    return HttpResponse('欢迎登录')